// 大屏监控系统JavaScript
class Dashboard {
    constructor() {
        this.currentWorkshop = '经编1';
        this.refreshInterval = 30000; // 30秒刷新一次
        this.timer = null;
        this.apiBaseUrl = '/api/dashboard';
        
        this.init();
    }

    // 初始化
    init() {
        this.updateTime();
        this.bindEvents();
        this.loadData();
        this.startAutoRefresh();
    }

    // 绑定事件
    bindEvents() {
        // 页面可见性变化时重新加载数据
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                this.loadData();
            }
        });
    }

    // 更新当前时间
    updateTime() {
        const now = new Date();
        const dateStr = now.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        });
        const timeStr = now.toLocaleTimeString('zh-CN', {
            hour12: false
        });

        document.getElementById('current-date').textContent = dateStr;
        document.getElementById('current-time').textContent = timeStr;

        // 每秒更新时间
        setTimeout(() => this.updateTime(), 1000);
    }



    // 加载所有数据
    async loadData() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/all-data?workshopType=${this.currentWorkshop}`);
            const result = await response.json();

            if (result.code === 200) {
                this.updateMachineTable(result.data.machineInfo);
                this.updateCustomMachineTable(result.data.customMachineInfo);
            } else {
                console.error('数据加载失败:', result.message);
                this.showError('数据加载失败: ' + result.message);
            }
        } catch (error) {
            console.error('网络错误:', error);
            this.showError('网络连接失败，请检查网络连接');
        }
    }

    // 更新机台信息表格
    updateMachineTable(machineInfoList) {
        const tbody = document.getElementById('machine-table-body');
        tbody.innerHTML = '';

        if (!machineInfoList || machineInfoList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #95a5a6;">暂无数据</td></tr>';
            return;
        }

        machineInfoList.forEach(machine => {
            const row = document.createElement('tr');
            
            // 根据剩余时间设置行样式
            const remainingTime = parseFloat(machine.remainingTime) || 0;
            if (remainingTime <= 1) {
                row.style.background = 'rgba(231, 76, 60, 0.2)';
            } else if (remainingTime <= 3) {
                row.style.background = 'rgba(243, 156, 18, 0.2)';
            }

            row.innerHTML = `
                <td>${machine.machineNo || ''}</td>
                <td>${machine.warpBeamNo || ''}</td>
                <td>${machine.materialName || ''}</td>
                <td>${machine.remainingTime || '0.0'}</td>
                <td>${machine.shaftChangeTime || ''}</td>
                <td>${machine.nextWarpingHeads || ''}</td>
            `;
            
            tbody.appendChild(row);
        });
    }

    // 更新自定义机台信息表格
    updateCustomMachineTable(customMachineInfoList) {
        const tbody = document.getElementById('custom-machine-table-body');
        tbody.innerHTML = '';

        if (!customMachineInfoList || customMachineInfoList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #95a5a6;">暂无自定义数据</td></tr>';
            return;
        }

        customMachineInfoList.forEach(machine => {
            const row = document.createElement('tr');
            
            // 根据剩余时间设置行样式
            const remainingTime = parseFloat(machine.remainingTime) || 0;
            if (remainingTime <= 1) {
                row.style.background = 'rgba(231, 76, 60, 0.2)';
            } else if (remainingTime <= 3) {
                row.style.background = 'rgba(243, 156, 18, 0.2)';
            }

            row.innerHTML = `
                <td>${machine.machineNo || ''}</td>
                <td>${machine.warpBeamNo || ''}</td>
                <td>${machine.materialName || ''}</td>
                <td>${machine.remainingTime || '0.0'}</td>
                <td>${machine.shaftChangeTime || ''}</td>
                <td>${machine.nextWarpingHeads || ''}</td>
            `;
            
            tbody.appendChild(row);
        });
    }


    // 显示错误信息
    showError(message) {
        // 可以在这里添加错误提示的UI
        console.error(message);
        
        // 简单的错误提示
        const errorDiv = document.createElement('div');
        errorDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #e74c3c;
            color: white;
            padding: 15px 20px;
            border-radius: 5px;
            z-index: 10000;
            font-size: 14px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        `;
        errorDiv.textContent = message;
        document.body.appendChild(errorDiv);

        // 3秒后自动移除
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 3000);
    }

    // 开始自动刷新
    startAutoRefresh() {
        if (this.timer) {
            clearInterval(this.timer);
        }
        
        this.timer = setInterval(() => {
            this.loadData();
        }, this.refreshInterval);
    }

    // 停止自动刷新
    stopAutoRefresh() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    // 销毁实例
    destroy() {
        this.stopAutoRefresh();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.dashboard = new Dashboard();
});

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
    if (window.dashboard) {
        window.dashboard.destroy();
    }
});
